

<template>
  <div class="single_screen" v-if="!user">
    <el-button type="primary" @click="getToken">Sign In</el-button>
  </div>
  <div class="multi-screen" v-else>
    <div class="title">Upload files</div>
    <el-upload
      v-model:file-list="fileList"
      class="upload-demo"
      action=""
      :show-file-list="false"
      :http-request="handleRequest"
    >
      <el-button type="primary">upload</el-button>
      <!-- <template #tip>
          <div class="el-upload__tip">
            jpg/png files with a size less than 500KB.
          </div>
        </template> -->
    </el-upload>
    <div class="title">
      Search for images：
      <el-select v-model="searchType" placeholder="Select" style="width: 340px">
        <el-option
          v-for="item in options"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        />
      </el-select>
    </div>

    <div v-if="searchType == 0">
      <p v-for="(item, index) in searchOption1.items" :key="index">
        Name：<el-input
          v-model="item.name"
          style="width: 240px"
          placeholder="Please enter a name"
          clearable
        />&nbsp;&nbsp;&nbsp;&nbsp;Quantity：<el-input
          v-model="item.num"
          style="width: 240px"
          placeholder="Please enter the quantity"
          clearable
        />&nbsp;&nbsp;&nbsp;&nbsp;
        <el-button
          type="info"
          circle
          v-if="
            searchOption1.items.length == 1
              ? false
              : index < searchOption1.items.length
          "
          @click="handleMinus(index)"
          >-</el-button
        >
        <el-button
          type="primary"
          circle
          v-if="index == searchOption1.items.length - 1"
          @click="handleAdd"
          >+</el-button
        >
      </p>
    </div>
    <div v-if="searchType == 1">
      <p v-for="(item, index) in searchOption2.items" :key="index">
        Name：<el-input
          v-model="item.name"
          style="width: 240px"
          placeholder="Please enter a name"
          clearable
        />&nbsp;&nbsp;&nbsp;&nbsp;
        <el-button
          type="info"
          circle
          v-if="
            searchOption2.items.length == 1
              ? false
              : index < searchOption2.items.length
          "
          @click="handleMinus2(index)"
          >-</el-button
        >
        <el-button
          type="primary"
          circle
          v-if="index == searchOption2.items.length - 1"
          @click="handleAdd2"
          >+</el-button
        >
      </p>
    </div>
    <!-- <div v-if="searchType == 2">
        <p>
          URL：<el-input
            v-model="searchOption3"
            style="width: 500px"
            placeholder="请输入图片URL"
            clearable
          />
        </p>
      </div> -->
    <div v-if="searchType == 3">
      <el-upload
        class="upload-demo"
        action=""
        :show-file-list="false"
        :http-request="handleRequest2"
      >
        <el-button type="primary">Upload file</el-button>
      </el-upload>
    </div>
    <el-button
      type="primary"
      @click="search"
      v-if="searchType !== 3"
      :disabled="getSearchState()"
      >Search</el-button
    >
    <div class="results">
      <span class="image-itm" v-for="(item, index) in results" :key="index">
        <a
          class="check"
          :class="imagesDel.map((itm) => itm.sl).includes(item) ? 'active' : ''"
          @click="appendDel(item)"
          ><em v-if="imagesDel.includes(item)">√</em></a
        >
        <img
          :src="item.includes('thumbnails') ? item : videoUrl"
          alt="暂无图片"
          @click="openImage(item)"
          width="200"
          height="200"
        />
      </span>
      <!-- <p v-if="results && results.length == 0">No data</p> -->
    </div>
    <el-button
      type="primary"
      @click="delResultImage"
      v-if="imagesDel && imagesDel.length > 0"
      >Batch Delete</el-button
    >
    <div class="title">Label Management</div>
    <div>
      <div>
        <div>Name and quantity</div>
        <p v-for="(item, index) in taglist.tags" :key="index">
          <el-input
            v-model="item.name"
            style="width: 240px"
            placeholder="Please enter a name"
            clearable
          />&nbsp;&nbsp;&nbsp;&nbsp;
          <el-input
            v-model="item.num"
            style="width: 240px"
            placeholder="Please enter the quantity"
            clearable
          />&nbsp;&nbsp;&nbsp;&nbsp;
          <el-button
            type="info"
            circle
            v-if="
              taglist.tags.length == 1 ? false : index < taglist.tags.length
            "
            @click="handleDeleteTag(1, index)"
            >-</el-button
          >
          <el-button
            type="primary"
            circle
            v-if="index == taglist.tags.length - 1"
            @click="handleAddTag(1)"
            >+</el-button
          >
        </p>
      </div>
      <div>
        <div>Url</div>
        <p v-for="(item, index) in taglist.urls" :key="index">
          <el-input
            v-model="item.name"
            style="width: 505px"
            placeholder="Please enter the URL"
            clearable
          />&nbsp;&nbsp;&nbsp;&nbsp;
          <el-button
            type="info"
            circle
            v-if="
              taglist.urls.length == 1 ? false : index < taglist.urls.length
            "
            @click="handleDeleteTag(2, index)"
            >-</el-button
          >
          <el-button
            type="primary"
            circle
            v-if="index == taglist.urls.length - 1"
            @click="handleAddTag(2)"
            >+</el-button
          >
        </p>
      </div>
    </div>

    <el-button type="primary" @click="handleTag(1)" :disabled="getTagdisabled()"
      >Add</el-button
    >
    <el-button type="info" @click="handleTag(0)" :disabled="getTagdisabled()"
      >Delete</el-button
    >
  </div>
</template>

<script setup>
import { reactive, ref, watch, onMounted } from "vue"
import { Plus } from '@element-plus/icons-vue'
import { searchImage, uploadFile, uploadAttribute, tagManage, deleteImage, uploadFileSearch } from "./api/index"
import { ElMessage } from 'element-plus'
import { signInRedirect, signOutRedirect, handleSigninCallback } from './auth'
import videoUrl from './assets/video.png'

import axios from "axios"



const user = ref(JSON.parse(localStorage.getItem('user')))
// let isToken = ref(false)

let fileList = reactive([])
let searchType = ref(0)
const options = [
  {
    value: 0,
    label: 'Query images and videos based on tags'
  },
  {
    value: 1,
    label: 'Based on bird species query files'
  },
  // {
  //   value: 2,
  //   label: '通过缩略图URL查询原图'
  // },
  {
    value: 3,
    label: 'File query'
  }
]

// const results = reactive({
//   imgList: [],
//   fileList: []
// })
const results = ref([])

const imagesDel = ref([])

const taglist = reactive(
  {
    tags: [
      {
        name: '',
        num: ''
      }
    ],
    urls: [
      {
        name: ''
      }
    ]
  }
)

// 查询按钮状态
const getSearchState = () => {
  if (searchType.value === 0) {
    const arr = searchOption1.items.map(item => Boolean(item.name) && Boolean(item.num))
    return arr.includes(false)
  }
  if (searchType.value == 1) {
    const arr = searchOption2.items.map(item => Boolean(item.name))
    return arr.includes(false)
  }
}

// 标签按钮状态
const getTagdisabled = () => {
  const arr1 = taglist.urls.map(item => Boolean(item.name))
  const arr2 = taglist.tags.map(item => Boolean(item.name) && Boolean(item.num))
  return [...arr1, ...arr2].includes(false)
}


// 新增标签行
const handleAddTag = (type) => {
  if (type === 1) {
    taglist.tags.push({
      name: '',
      num: ''
    })
  } else {
    taglist.urls.push({
      name: ''
    })
  }
}
// 删除选择的标签
const handleDeleteTag = (type, index) => {
  if (type === 1) {
    taglist.tags.splice(index, 1)
  } else {
    taglist.urls.splice(index, 1)
  }
}
//标签新增和删除
const handleTag = async (type) => {
  let arr = ref([])
  taglist.tags.forEach(item => {
    if (item.name != '' && item.num != '') {
      // obj[item.name] = item.num
      let obj = `${item.name},${item.num}`
      arr.value.push(obj)
    }
  })
  try {
    const res = await tagManage({
      action: 'tag_edit',
      operation: type,
      url: taglist.urls.filter(itm => itm.name != '').map(item => item.name),
      tags: arr.value
    })
    taglist.urls = [
      { name: '' }
    ]
    taglist.tags = [
      { name: '', num: '' }
    ]
    ElMessage(res?.message)
  } catch (err) {
    console.log(err)
  }


}
// 监听要选择的类型搜索并清除已配置搜索条件和查询结果
watch(searchType, () => {
  searchOption1.items = [
    { name: '', num: '' }
  ]
  searchOption2.items = [
    { name: '' }
  ]
  searchOption3.value = ''
  searchOption4.value = ''
  // results.imgList = []
  // results.fileList = []
  results.value = []
})

let searchOption1 = reactive({
  items: [
    { name: '', num: '' }
  ]
})
let searchOption2 = reactive({
  items: [
    { name: '' }
  ]
})
let searchOption3 = ref('')
let searchOption4 = ref('')


// 批量选择要删除的文件
const appendDel = async (url, index) => {

  let tempUrl = await getYSURL(url)
  const arr = imagesDel.value.filter(item => item.sl)
  if (arr.includes(url)) {
    imagesDel.value = imagesDel.value.filter(item => item.sl != url)
  } else {
    imagesDel.value.push({
      sl: url,
      ys: tempUrl
    })
  }
  console.log(imagesDel.value)
}

const getYSURL = async (url) => {
  let tempUrl = ref('')
  if (url.includes('thumbnails')) {
    try {
      const res = await searchImage({
        action: 'thumbnail',
        thumbnail: url
      })
      tempUrl.value = res['s3-url']
    } catch (err) {
      console.log(err)
    }
  } else {
    tempUrl.value = url
  }
  return tempUrl.value
}

// 查询新增名称加数量
const handleAdd = () => {
  searchOption1.items.push({ name: '', num: '' })
}
// 查询删除名称加数量
const handleMinus = (index) => {
  searchOption1.items.splice(index, 1)
}
// 查询新增名称
const handleAdd2 = () => {
  searchOption2.items.push({ name: '' })
}
// 查询删除名称
const handleMinus2 = (index) => {
  searchOption2.items.splice(index, 1)
}

// 查询
const search = async () => {
  let params = reactive({
    action: '',
    tags: {}
  })
  if (searchType.value === 0) {
    let tagsObj = reactive({})
    searchOption1.items.forEach((element, index) => {
      let obj = {}
      obj[element.name] = element.num
      tagsObj = { ...tagsObj, ...obj }
    })
    params = {
      action: 'search_with_count',
      tags: tagsObj
    }
  }
  if (searchType.value === 1) {
    let tags = ref([])
    params = {
      action: 'search_no_count',
      tags: searchOption2.items.map(item => item.name)
    }
  }
  if (searchType.value === 2) {
    params = {
      action: 'thumbnail',
      thumbnail: searchOption3.value
    }
  }
  try {
    if (searchType.value === 0 || searchType.value === 1) {
      const { links } = await searchImage(params)
      // results.imgList = (links || []).filter(item => item.includes('thumbnails'))
      // console.log(results.imgList)
      // results.fileList = (links || []).filter(item => !item.includes('thumbnails'))
      results.value = links || []
    }

  } catch (err) {
    console.log(err)
  }

}

// 批量删除图片
const delResultImage = async () => {
  try {
    const res = await deleteImage({
      action: 'delete',
      urls: imagesDel.value.map(item => item.ys)
    })
    imagesDel.value = []
    search()
    ElMessage(res?.message)
  } catch (err) {
    console.log(err)
  }
}

// 打开图片
const openImage = async (url) => {
  console.log(url)
  if (url.includes('thumbnails')) {
    try {
      const res = await searchImage({
        action: 'thumbnail',
        thumbnail: url
      })
      window.open(res['s3-url'], '_blank')
    } catch (err) {
      console.log(err)
    }
  } else {
    downloadFile('test', url)
  }

}

const downloadFile = (name, url) => {
  console.log(name, url)
  const a = document.createElement('a')
  a.href = url
  a.download = name
  a.click()
  a.remove() // 移除掉 <a>
}

// 获取token
const getToken = async () => {
  await signInRedirect()
}



// 自定义上传文件
const handleRequest = async (options) => {
  const { file } = options
  let params = ref(null)
  console.log(file)
  // console.log(file)
  if (file.type.includes('image')) {
    params = {
      type: 'images',
      suffix: file.type.split('/')[1],
      filename: file.name
    }
  }
  if (file.type.includes('audio')) {
    params = {
      type: 'audio',
      suffix: file.type.split('/')[1],
      filename: file.name
    }
  }
  if (file.type.includes('video')) {
    params = {
      type: 'videos',
      suffix: file.type.split('/')[1],
      filename: file.name
    }
  }
  try {
    // const formData = new FormData()
    // formData.append('file', file)
    const res = await uploadAttribute(params)
    await uploadFile(file, res.url, res.content_type)
    ElMessage('success')
  } catch (err) {
    console.log(err)
  }
}

// 上传文件查询
const handleRequest2 = async (options) => {
  const { file } = options
  console.log(file)
  let formData = new FormData()
  formData.append('file', file)
  formData.append('name', file.name)
  console.log(file)
  try {
    const res = await uploadFileSearch(formData)
    // results.value = [res.url]
    console.log(res)
  } catch (err) {
    console.log(err)
  }
  // axios.post('https://p1u1kegp32.execute-api.us-east-1.amazonaws.com/prod1/api/query/query_by_file', file, {
  //   headers: {
  //     'Authorization': JSON.parse(localStorage.getItem('user')).id_token,
  //     'Content-Type': file.type,
  //   },
  // }).then(res => {
  //   console.log(res)
  // })
}



// 处理回调并获取用户信息
onMounted(async () => {
  const userData = await handleSigninCallback()
  if (userData) {
    user.value = userData
    localStorage.setItem('user', JSON.stringify(user.value))
  }
});
</script>

<style scoped>
.page {
  padding: 0 20px;
}

.single_screen {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
}

.multi-screen {
  padding: 0 20px;
}

.title {
  border-bottom: 1px solid #cccccc;
  margin: 20px 0;
  padding: 5px 0;
  font-size: 18px;
}
.results {
  display: flex;
  padding: 20px 0;
}

.results .image-itm {
  margin: 5px;
  position: relative;
}

.check {
  position: absolute;
  right: 5px;
  top: 5px;
  z-index: 9;
  width: 20px;
  height: 20px;
  border-radius: 50%;
  background: #cccccc;
  border: 2px solid #ffffff;
  text-align: center;
}

.check.active {
  background: green;
}

.check em {
  color: #ffffff;
  position: relative;
  font-size: 12px;
  font-weight: bold;
  top: -2px;
}

.results img {
}
</style>
